using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class UI_Dialogue : MonoBehaviour
{
    [SerializeField] private TextMeshProUGUI dialogueText;
    [SerializeField] private TextMeshProUGUI speakerName;
    [SerializeField] private Image speakerPortrait;
    [SerializeField] private TextMeshProUGUI[] dialogueChoice;

    [SerializeField] private float interval = .1f;
    private UI uI;
    private Coroutine typeTextCo;
    private string fullLineText;
    private bool waitingToConfirm; //当对话文字全部显示出来后为true，用于判断下一次使用enter键
                                   //如果下一次使用enter键（即确认所选择的回答）为true时，确认回答，确认完成后设为false
                                   //上下选择键只有waitingToConfirm为true（即当对话文字全部显示出来后响应）时才能响应
                                    //每次开始对话时重置为false
    private DialogueLineSO currentLine;
    private DialogueLineSO[] allchoices;
    private DialogueLineSO selectedChoice;
    private int selectedChoicesIndex;
    private DialogueNPCData dialogueNPCData;
    private PlayerQuestManager questManager;
    private void Awake()
    {
        uI = GetComponentInParent<UI>();
        questManager = Player.Instance.questManager;
    }
    public void SetupDialogueUI(DialogueNPCData dialogueNPCData) => this.dialogueNPCData = dialogueNPCData;
    public void PlayerDialogueLine(DialogueLineSO line)
    {
        //每次打开对话重置
        selectedChoicesIndex = 0;
        waitingToConfirm = false;

        currentLine = line;
        allchoices = line.choiceLines;
        speakerName.text = line.dialogueGroupName;
        speakerPortrait.sprite = line.speaker.speakerProtrait;

        UpdateDialogue();

        foreach (var choice in dialogueChoice)
            choice.gameObject.SetActive(false);
    }

    public void DialogueInteraction()
    {
        if (typeTextCo != null && fullLineText.Length > 5)
        {
            //补全对话内容
            CompleteText();
            return;
        }
        if (waitingToConfirm)
        {
            waitingToConfirm = false;
            StartHandleNextHandle();
        }
    }
    public void NaivgationChoice(int dirction)
    {
        if (allchoices == null || allchoices.Length <= 1 )
            return;

        if (waitingToConfirm == false)
            return;
        selectedChoicesIndex += dirction;
        selectedChoicesIndex = Mathf.Clamp(selectedChoicesIndex, 0, allchoices.Length - 1);
        UpdateChoice();
    }
    //更新对话
    private void UpdateDialogue()
    {
        fullLineText = currentLine.dialogueType == DialogueActionType.None || currentLine.dialogueType == DialogueActionType.PlayerMakeChoice ? currentLine.GetRandomLine() : currentLine.actionLine[0];

        if (currentLine.dialogueType == DialogueActionType.GetQuestReward && questManager.IsFinishQuest(dialogueNPCData.rewardType) == false)
            fullLineText = currentLine.actionLine[1];
        if (currentLine.dialogueType == DialogueActionType.OpenQuest && questManager.HasQuestInRewardType(dialogueNPCData.rewardType) == false)
            fullLineText = currentLine.actionLine[1];

        typeTextCo = StartCoroutine(TypeTextCo(fullLineText));
    }
    //补全对话内容
    private void CompleteText()
    {
        StopCoroutine(typeTextCo);
        dialogueText.text = fullLineText;

        ResetBeforeNextAction();
    }

    private IEnumerator TypeTextCo(string lineText)
    {
        dialogueText.text = "";
        foreach (var @char in lineText)
        {
            dialogueText.text += @char;
            yield return new WaitForSeconds(interval);
        }

        ResetBeforeNextAction();
    }
    //在做出下一个行动前重置选项
    private void ResetBeforeNextAction()
    {
        typeTextCo = null;

        if (currentLine.dialogueType == DialogueActionType.PlayerMakeChoice)
            selectedChoice = null;
        StartHandleNextHandle();
    }
    //延迟显示回答选择
        
    //更新回答选择
    private void UpdateChoice()
    {
        for (int i = 0; i < dialogueChoice.Length; i++)
        {
            if (i < allchoices.Length)
            {
                dialogueChoice[i].gameObject.SetActive(true);

                string choiceText = allchoices[i].choice;

                //判断是否是当前悬停的选择
                dialogueChoice[i].text = i == selectedChoicesIndex ?
                    $"<color=yellow> {i + 1}) {choiceText}</color>" : $"{i + 1}) {choiceText}";
                continue;
            }
            dialogueChoice[i].gameObject.SetActive(false);
        }
        //设置当前的选择
        selectedChoice = allchoices[selectedChoicesIndex];
    }
    //处理当前对话的下一步

    private void StartHandleNextHandle()
    {
        waitingToConfirm = true;
        StartCoroutine(HandleNextAction());
    }
    private IEnumerator HandleNextAction()
    {
        switch (currentLine.dialogueType)
        {
            case DialogueActionType.OpenCraft:
                yield return new WaitForSeconds(.5f);
                uI.SwitchPanelToInGame();
                uI.OpenCraftAndStorageUI(true);
                yield break;

            case DialogueActionType.PlayerMakeChoice:
                if (selectedChoice == null)
                {
                    yield return new WaitForSeconds(.5f);
                    UpdateChoice();
                }
                else
                {
                    PlayerDialogueLine(selectedChoice);
                    selectedChoice = null;
                }
                yield break;

            case DialogueActionType.OpenShop:
                yield return new WaitForSeconds(.5f);
                uI.SwitchPanelToInGame();
                uI.OpenMerchantUI(true);
                yield break;

            case DialogueActionType.CloseDialogue:
                yield return new WaitForSeconds(.5f);
                uI.SwitchPanelToInGame();
                yield break;

            case DialogueActionType.OpenQuest:
                yield return new WaitForSeconds(.5f);
                uI.SwitchPanelToInGame();
                if (questManager.HasQuestInRewardType(dialogueNPCData.rewardType))
                    uI.OpenQuestUI(dialogueNPCData.questDatas);
                yield break;

            case DialogueActionType.GetQuestReward:
                yield return new WaitForSeconds(.5f);
                uI.SwitchPanelToInGame();
                questManager.TryGiveRewardFrom(dialogueNPCData.rewardType);
                yield break;
            case DialogueActionType.None:
                PlayerDialogueLine(selectedChoice);
                break;
            default:
                yield break;
        }

    }
}
